package com.itheim.aop;

import com.itheim.mapper.OperateLogMapper;
import com.itheim.pojo.OperateLog;
import com.itheim.mapper.OperateLogMapper;
import com.itheim.util.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheim.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        String methodParams = Arrays.toString(joinPoint.getArgs());

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object returnValue = joinPoint.proceed();

        // 记录结束时间
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;

        // 构造操作日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentEmpId()); // 获取当前操作人ID
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(methodParams);
        operateLog.setReturnValue(returnValue != null ? returnValue.toString() : null);
        operateLog.setCostTime(costTime);

        // 保存操作日志
        operateLogMapper.insert(operateLog);

        return returnValue;
    }

    // 模拟获取当前操作人ID的方法
    private Integer getCurrentEmpId() {
        // 这里可以根据实际情况获取当前操作人ID，比如从Session中获取
        return CurrentHolder.getCurrentId(); // 假设当前操作人ID为1
    }
}
